﻿using Newtonsoft.Json;
using System.Collections.Concurrent;
using System.Text.RegularExpressions;
using Yitter.IdGenerator;

namespace WorkerService2024
{
    public class Worker : BackgroundService
    {
        private readonly ILogger<Worker> _logger;

        public Worker(ILogger<Worker> logger)
        {
            _logger = logger;
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {

            #region 音乐名称修改
            //YitIdHelper.SetIdGenerator(new IdGeneratorOptions()
            //{
            //    Method = 1,
            //    WorkerId = 1,

            //    WorkerIdBitLength = 6,
            //    SeqBitLength = 6,
            //    DataCenterIdBitLength = 0,
            //    TopOverCostCount = 2000,

            //    //TimestampType = 1,
            //    // MinSeqNumber = 1,
            //    // MaxSeqNumber = 200,
            //    // BaseTime = DateTime.Now.AddYears(-10),
            //});
            //var topFilePath = "F:\\抖音\\TikTokDownloaderByDev";
            //var directs = Directory.GetDirectories(topFilePath);
            //foreach (var direct in directs)
            //{
            //    if (direct.ToString().Contains("MID") || direct.ToString().Contains("UID"))
            //    {
            //        string[] files = Directory.GetFiles(direct);
            //        foreach (string file in files)
            //        {
            //            // 获取文件名（包含扩展名）
            //            string fileName = Path.GetFileName(file);
            //            string tempFileName = fileName;
            //            var tempPrefix = fileName.Substring(0, 19);
            //            if (long.TryParse(tempPrefix, out long preFix))
            //                fileName = fileName.Substring(19, fileName.Length - 19);
            //            fileName = fileName.Replace("《", string.Empty).Replace("》", string.Empty)
            //                .Replace("，", "_").Replace("#", "_").Replace("-", "_").Replace(".mp3", string.Empty)
            //                .Replace(" ", string.Empty).Replace("；", string.Empty).Replace("！", string.Empty).Replace("？", string.Empty).Replace("。", "_").Replace("\\", string.Empty).Replace("/", string.Empty)
            //                .Replace("@", string.Empty).Replace("+", string.Empty).Replace("!", string.Empty).Replace("...", string.Empty)
            //                 .Replace("、", string.Empty).Replace(".", string.Empty)
            //                 .Replace("“", string.Empty).Replace("”", string.Empty).Replace("ᇂ", string.Empty).Replace("=", string.Empty).Replace("…", string.Empty)
            //                 .Replace("～", string.Empty).Replace("车载", string.Empty).Replace("u盘", string.Empty).Replace("U盘", string.Empty)
            //                 .Replace("๑҉꯭", string.Empty).Replace("๑҉꯭", string.Empty)
            //                .Replace("小助手", string.Empty).Replace("DOU", string.Empty).Replace("+", string.Empty).Replace("）", string.Empty)
            //                .Replace("?", "_").Replace("(", string.Empty).Replace(")", string.Empty).Replace("（", string.Empty).Replace("__", "_").Replace("__", "_").Replace("__", "_").Replace("__", "_").Trim('_');

            //            fileName = Regex.Replace(fileName, @"[^\u4e00-\u9fff\w]", "").Replace("__", "_").Replace("__", "_").Replace("__", "_").Replace("__", "_").Trim('_');
            //            var isDJ = fileName.ToLower().Contains("dj");
            //            if (isDJ)
            //                fileName = fileName.Replace("DJ", string.Empty).Replace("dj", string.Empty).Replace("Dj", string.Empty).Replace("dJ", string.Empty);
            //            if (tempFileName == fileName) continue;
            //            // 这里可以根据你的需求自定义新的文件名
            //            string newFilePath = Path.Combine(direct, $"{new Random().Next(10000, 99999)}_{fileName}{(isDJ ? "dj" : default)}_{YitIdHelper.NextId()}.mp3");

            //            File.Move(file, newFilePath, true);
            //        }
            //    }
            //}

            //foreach (var oldDirect in directs)
            //{
            //    if (oldDirect.ToString().Contains("MID") || oldDirect.ToString().Contains("UID"))
            //    {
            //        string[] files = Directory.GetFiles(oldDirect);
            //        var oldDirectName = Path.GetFileName(oldDirect);
            //        var newDirectName = $"{oldDirectName}_{files.Length}";
            //        var newDirect = oldDirect.Replace(oldDirectName, newDirectName);
            //        Directory.Move(oldDirect, newDirect);
            //    }
            //}
            #endregion

            #region Parallel
            //var numbers = Enumerable.Range(1, 100).ToList();
            //Parallel.ForEach(numbers, (num) =>
            //{
            //    // 执行并行操作
            //    Console.WriteLine(num);
            //});

            //var result = from num in numbers.AsParallel()
            //             where num % 2 == 0
            //             select num;

            //Parallel.Invoke(
            //    () =>
            //    {
            //        Console.WriteLine(1111);
            //    },
            //    () =>
            //    {
            //        Console.WriteLine(2222);
            //    },
            //    () =>
            //    {
            //        Console.WriteLine(3333);
            //    }
            //);

            //var partitioner = Partitioner.Create(numbers, true);
            //Parallel.ForEach(partitioner, (num) =>
            //{
            //    // 执行并行操作
            //    Console.WriteLine(num);
            //});

            #endregion

            #region Mqtt

            //await Program.Provider.GetService<TestAMqttHost>().StartAsync(stoppingToken);
            //await Program.Provider.GetService<TestBMqttHost>().StartAsync(stoppingToken);

            #endregion Mqtt

            #region WebSocket

            //await Program.Provider.GetService<TestWebSocketAHost>().StartAsync(stoppingToken);
            //await Program.Provider.GetService<TestWebSocketBHost>().StartAsync(stoppingToken);

            #endregion WebSocket

            #region Socket

            //await Program.Provider.GetService<TestSocketAHost>().StartAsync(stoppingToken);
            //await Program.Provider.GetService<TestSocketBHost>().StartAsync(stoppingToken);

            #endregion Socket

            #region 暂时注释

            while (!stoppingToken.IsCancellationRequested)
            {
                _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
                await Task.Delay(1000, stoppingToken);
            }

            #endregion 暂时注释
        }
    }
}